package com.example.myapplication.function.musicmode

/**
 * 2. 增强的音高检测和旋律分析
 */
class EnhancedMelodyAnalyzer {
    private val pitchDetector = PitchDetector()
    private val scaleSystem = ScaleTheorySystem()
    
    data class MelodyAnalysisResult(
        val detectedNotes: List<String>,
        val keyResults: List<ScaleTheorySystem.KeyDetectionResult>,
        val mostLikelyKey: ScaleTheorySystem.KeyDetectionResult?,
        val noteDistribution: Map<String, Int>,
        val tempo: Double,
        val confidence: Double
    )
    
    // 分析哼唱的旋律
    fun analyzeMelody(audioData: List<FloatArray>): MelodyAnalysisResult {
        // 1. 检测所有音高
        val allFrequencies = audioData.mapNotNull { pitchDetector.detectPitch(it) }
        
        // 2. 转换为音符名称 (去除八度信息)
        val noteNames = allFrequencies.map { pitchDetector.frequencyToNote(it) }
            .map { it.replace("\\d".toRegex(), "") } // 移除数字，只保留音符名称
        
        // 3. 统计音符分布
        val noteDistribution = noteNames.groupingBy { it }.eachCount()
        
        // 4. 检测调式
        val keyResults = scaleSystem.detectKey(noteNames.distinct())
        val mostLikelyKey = keyResults.firstOrNull()
        
        // 5. 计算整体置信度
        val confidence = calculateOverallConfidence(noteNames, mostLikelyKey)
        
        // 6. 估算节奏
        val tempo = estimateTempo(audioData)
        
        return MelodyAnalysisResult(
            detectedNotes = noteNames,
            keyResults = keyResults,
            mostLikelyKey = mostLikelyKey,
            noteDistribution = noteDistribution,
            tempo = tempo,
            confidence = confidence
        )
    }
    
    // 实时分析（用于实时显示）
    fun analyzeRealTime(audioData: FloatArray): RealTimeAnalysis? {
        val frequency = pitchDetector.detectPitch(audioData) ?: return null
        val noteName = pitchDetector.frequencyToNote(frequency)
            .replace("\\d".toRegex(), "")
        
        return RealTimeAnalysis(
            currentNote = noteName,
            frequency = frequency,
            confidence = pitchDetector.calculateAccuracy(frequency, noteName)
        )
    }
    
    data class RealTimeAnalysis(
        val currentNote: String,
        val frequency: Double,
        val confidence: Double
    )
    
    private fun calculateOverallConfidence(
        notes: List<String>, 
        keyResult: ScaleTheorySystem.KeyDetectionResult?
    ): Double {
        if (notes.isEmpty()) return 0.0
        
        val keyConfidence = keyResult?.confidence ?: 0.0
        val noteStability = calculateNoteStability(notes)
        
        // 综合调式匹配度和音符稳定性
        return (keyConfidence * 0.7 + noteStability * 0.3)
    }
    
    private fun calculateNoteStability(notes: List<String>): Double {
        if (notes.size < 2) return 0.0
        
        // 计算音符变化的稳定性
        var changes = 0
        for (i in 1 until notes.size) {
            if (notes[i] != notes[i-1]) {
                changes++
            }
        }
        
        val changeRate = changes.toDouble() / (notes.size - 1)
        return 1.0 - changeRate // 变化越少越稳定
    }
    
    private fun estimateTempo(audioData: List<FloatArray>): Double {
        // 简化的节奏估算（基于音频块的数量和时间）
        val totalDuration = audioData.size * 0.1 // 假设每个块0.1秒
        val estimatedNotes = audioData.size / 5.0 // 估算音符数量
        
        return (estimatedNotes / totalDuration) * 60.0 // 转换为BPM
    }
}